<?php
	/*
	* This script creates a [project_name].csv file tha contains data taken from MySQL db and attaches it to the header of the page so it is downloadable.
	* The user is promted to choose name the file ans choose a folder/path to save it in.
	* @method GET
	* @header pname Current project name
	*  
	*/

	require_once("../functions/connect_to_database.php");

	// Grab the project name
	$project_name = mysql_real_escape_string($_GET['project_name']);
	
	/*Output [$project_name] table to .csv file */
	$result = mysql_query("SELECT * FROM `$project_name`"); 
	if (!$result) die('Couldn\'t fetch records'); 
	$num_fields = mysql_num_fields($result); 
	$headers = array(); 
	for ($i = 0; $i < $num_fields; $i++) 
	{     
	       $headers[] = mysql_field_name($result , $i); 
	} 
	$fp = fopen('php://output', 'w'); 
	if ($fp && $result) 
	{     
	       header('Content-Type: text/csv');
	       header('Content-Disposition: attachment; filename="'.$project_name.'.csv"');
	       header('Pragma: no-cache');    
	       header('Expires: 0');
	       fputcsv($fp, $headers); 
	       while ($row = mysql_fetch_row($result)) 
	       {
	          fputcsv($fp, array_values($row)); 
	       }
	die; 
	}
	
?>